<template>
    <div :class="classes">
        <input type="hidden" v-if="name && onlyOne" :name="hideName" v-model="currentValue">
        <input type="hidden" v-if="name && !onlyOne" :name="hideName" v-for="value in currentValue" v-model="value">
        <slot></slot>
    </div>
</template>
<script>
    import {findComponentsDownward} from '../../utils/assist';
    import Emitter from '../../mixins/emitter';
    const prefixCls = 'ivu-checkbox-group';

    export default {
        name: 'CheckboxGroup',
        mixins: [Emitter],
        props: {
            name: String,
            value: [Array, String]
        },
        data () {
            return {
                currentValue: this.value,
                childrens: []
            };
        },
        computed: {
            classes () {
                return `${prefixCls}`;
            },
            hideName(){
                if (this.name)return this.name.split(",")[0];
                return "";
            },
            onlyOne(){
                if (this.name && this.name.indexOf(",") == -1)return true;
                return false;
            }
        },
        mounted () {
            if (!this.value) {//值为空，则设置默认存储数组
                this.currentValue = [];
            } else {
                const type = typeof this.value;
                if (type === 'string') {//值为字符串，则解析为数组
                    this.currentValue = this.value.split(",");
                }
            }
            this.updateModel(true);
        },
        methods: {
            updateModel (update) {
                const value = this.currentValue;
                this.childrens = findComponentsDownward(this, 'Checkbox');

                if (this.childrens) {
                    this.childrens.forEach(child => {
                        child.model = value;

                        if (update) {
                            child.currentValue = value.indexOf(child.value) >= 0;
                            child.group = true;
                        }
                    });
                }
            },
            change (data) {
                this.currentValue = data;
                this.updateModel();
                this.$emit('input', data);
                this.$emit('on-change', data);
                this.dispatch('FormItem', 'on-form-change', data);
            }
        },
        watch: {
            value (val) {
                this.currentValue = val;
                this.updateModel(true);
            }
        }
    };
</script>
